#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QJsonDocument>
#include<QJsonObject>
#include<QJsonArray>


#define INCREEMENT 3    //温度每升高/降低1°，Y轴坐标的增量
#define POINT_RADIUS 3   //曲线描点的大小
#define TEXT_OFFSET_X 12
#define TEXT_OFFSET_Y 12

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowFlag(Qt::FramelessWindowHint); //设置窗口无边框
    setFixedSize(800,500);

    connect(ui->pushButton_exict,&QPushButton::clicked,this,&QWidget::close);    //退出
    mNetworkAccessManager=new QNetworkAccessManager(this);

    connect(mNetworkAccessManager,&QNetworkAccessManager::finished,this,&MainWindow::onReplied);

    getWeatherInfo("西安");//默认

    ui->lblHighCurve->installEventFilter(this);
    ui->lblLowCurve->installEventFilter(this);


    mWeekList<<ui->lblWeek0<<ui->lblWeek1<<ui->lblWeek2<<ui->lblWeek3<<ui->lblWeek4<<ui->lblWeek5;
    mDateList<<ui->lblDate0<<ui->lblDate1 <<ui->lblDate2<<ui->lblDate3<<ui->lblDate4<<ui->lblDate5;
    mIconList<<ui->lblTypeIcon0 <<ui->lblTypeIcon1<<ui->lblTypeIcon2<<ui->lblTypeIcon3<<ui->lblTypeIcon4<<ui->lblTypeIcon5;
    mTypeList<<ui->lblType0<<ui->lblType1<<ui->lblType2<<ui->lblType3<<ui->lblType4<<ui->lblType5;
    mAqiList<<ui->lblQuality0<<ui->lblQuality1<<ui->lblQuality2<<ui->lblQuality3<<ui->lblQuality4<<ui->lblQuality5;
    mFxList<<ui->lblFx0<<ui->lblFx1 <<ui->lblFx2 <<ui->lblFx3 <<ui->lblFx4<<ui->lblFx5;
    mFlList<<ui->lblFl0 <<ui->lblFl1<<ui->lblFl2<<ui->lblFl3<<ui->lblFl4 <<ui->lblFl5;

    mTypeMap.insert("暴雪",":/res/type/BaoXue.png");
    mTypeMap.insert("暴雨",":/res/type/BaoYu.png");
    mTypeMap.insert("暴雨到大暴雨",":/res/type/BaoYuDaoDaBaoYu.png");
    mTypeMap.insert("大暴雨",":/res/type/DaBaoYu.png");
    mTypeMap.insert("大暴雨到特大暴雨",":/res/type/DaBaoYuDaoTeDaBaoYu.png");
    mTypeMap.insert("大到暴雪",":/res/type/DaDaoBaoXue.png");
    mTypeMap.insert("大到暴雨",":/res/type/DaDaoBaoYu.png");
    mTypeMap.insert("大雪",":/res/type/DaXue.png");
    mTypeMap.insert("大雨",":/res/type/DaYu.png");
    mTypeMap.insert("冻雨",":/res/type/DongYu.png");
    mTypeMap.insert("多云",":/res/type/DuoYun.png");
    mTypeMap.insert("浮沉",":/res/type/FuChen.png");
    mTypeMap.insert("雷阵雨",":/res/type/LeiZhenYu.png");
    mTypeMap.insert("雷阵雨伴有冰雹",":/res/type/LeiZhenYuBanYouBingBao.png");
    mTypeMap.insert("霾",":/res/type/Mai.png");
    mTypeMap.insert("强沙尘暴",":/res/type/QiangShaChenBao.png");
    mTypeMap.insert("晴",":/res/type/Qing.png");
    mTypeMap.insert("沙尘暴",":/res/type/ShaChenBao.png");
    mTypeMap.insert("特大暴雨",":/res/type/TeDaBaoYu.png");
    mTypeMap.insert("undefined",":/res/type/undefined.png");
    mTypeMap.insert("雾",":/res/type/Wu.png");
    mTypeMap.insert("小到中雪",":/res/type/XiaoDaoZhongXue.png");
    mTypeMap.insert("小到中雨",":/res/type/XiaoDaoZhongYu.png");
    mTypeMap.insert("小雪",":/res/type/XiaoXue.png");
    mTypeMap.insert("小雨",":/res/type/XiaoYu.png");
    mTypeMap.insert("雪",":/res/type/Xue.png");
    mTypeMap.insert("扬沙",":/res/type/YangSha.png");
    mTypeMap.insert("阴",":/res/type/Yin.png");
    mTypeMap.insert("雨",":/res/type/Yu.png");
    mTypeMap.insert("雨夹雪",":/res/type/YuJiaXue.png");
    mTypeMap.insert("阵雪",":/res/type/ZhenXue.png");
    mTypeMap.insert("阵雨",":/res/type/ZhenYu.png");
    mTypeMap.insert("中到大雪",":/res/type/ZhongDaoDaXue.png");
    mTypeMap.insert("中到大雨",":/res/type/ZhongDaoDaYu.png");
    mTypeMap.insert("中雪",":/res/type/ZhongXue.png");
    mTypeMap.insert("中雨",":/res/type/ZhongYu.png");

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::mousePressEvent(QMouseEvent *event)
{
    mOffset =  event->globalPos()- this->pos();
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos()-mOffset);

}



void MainWindow::getWeatherInfo(QString cityName)
{
    QString cityCode= weatherTool::getCityCode(cityName);
    if(cityCode.isEmpty())
    {
        QMessageBox::warning(this,"天气","请检查是否正确",QMessageBox::Ok);
        return;
    }
    QUrl mUrl("http://t.weather.itboy.net/api/weather/city/"+cityCode);
    mNetworkAccessManager->get(QNetworkRequest(mUrl));
}


void MainWindow::parseJson(QByteArray & mByteArray)
{
    QJsonParseError mError;
    QJsonDocument mDoc= QJsonDocument::fromJson(mByteArray,&mError);
    if(mError.error!=QJsonParseError::NoError)
    {
        return;
    }
    //根据对象层级
    QJsonObject mRootObj=mDoc.object();                             //1
    QJsonObject objCity=mRootObj.value("cityInfo").toObject();      //1.1
    QJsonObject objData=mRootObj.value("data").toObject();          //1.2
    QJsonObject objYesterday=objData.value("yesterday").toObject(); //Yesterday
    QJsonArray forcastArray=objData.value("forecast").toArray();    //1.1.1

//class today weather
     mTodayWeather.date=mRootObj.value("date").toString();           //1
     mTodayWeather.city=objCity.value("city").toString();            //1.1
     mTodayWeather.ganmao=objData.value("ganmao").toString();        //1.2
     mTodayWeather.wendu=objData.value("wendu").toString();
     mTodayWeather.shidu=objData.value("shidu").toString();
     mTodayWeather.pm25=objData.value("pm25").toInt();
     mTodayWeather.quality=objData.value("quality").toString();

    QJsonObject objForcastArray=forcastArray[1].toObject();         //1.1.1.1
     mWeekWeather[1].type=objForcastArray.value("type").toString();
     mWeekWeather[1].fl=objForcastArray.value("fl").toString();
     mWeekWeather[1].fx=objForcastArray.value("fx").toString();

//class today weather yestaeday

    mWeekWeather[0].date=objYesterday.value("ymd").toString();
    mWeekWeather[0].week=objYesterday.value("week").toString();
    mWeekWeather[0].type=objYesterday.value("type").toString();

    QString sJson;
    sJson=objYesterday.value("high").toString().split(" ").at(1);
    sJson=sJson.left(sJson.length()-1);
    mWeekWeather[0].high=sJson.toInt();
    sJson=objYesterday.value("low").toString().split(" ").at(1);
    sJson=sJson.left(sJson.length()-1);
    mWeekWeather[0].low=sJson.toInt();

    mWeekWeather[0].fl=objYesterday.value("fl").toString();
    mWeekWeather[0].fx=objYesterday.value("fx").toString();
    mWeekWeather[0].aqi=objYesterday.value("aqi").toInt();
//class week weather

    for(int i=0;i<5;i++)
    {
        QJsonObject objForcastArray=forcastArray[i].toObject();
        mWeekWeather[i+1].date=objForcastArray.value("ymd").toString();
        mWeekWeather[i+1].week=objForcastArray.value("week").toString();
        mWeekWeather[i+1].type=objForcastArray.value("type").toString();


        sJson=objForcastArray.value("high").toString().split(" ").at(1);
        sJson=sJson.left(sJson.length()-1);
        mWeekWeather[i+1].high=sJson.toInt();

        sJson=objForcastArray.value("low").toString().split(" ").at(1);
        sJson=sJson.left(sJson.length()-1);
        mWeekWeather[i+1].low=sJson.toInt();


        mWeekWeather[i+1].fl=objForcastArray.value("fl").toString();
        mWeekWeather[i+1].fx=objForcastArray.value("fx").toString();
        mWeekWeather[i+1].aqi=objForcastArray.value("aqi").toInt();
    }


    updateUi();
    ui->lblHighCurve->update();
    ui->lblLowCurve->update();

}




void MainWindow::updateUi()
{
    ui->lblDate->setText(QDateTime::fromString(mTodayWeather.date,"yyyyMMdd").toString("yyyy/MM/dd")+" "+mWeekWeather[1].week);
    ui->lblCity->setText(mTodayWeather.city);
    ui->lblTemp->setText(mTodayWeather.wendu);
    ui->lblType->setText(mTodayWeather.type);

    ui->lblLowHigh->setText(QString::number(mWeekWeather[0].low)+"C°～"+QString::number(mWeekWeather[0].high)+"C°");

    ui->lblGanMao->setText(mTodayWeather.ganmao);
    ui->lblWindFl->setText(mWeekWeather[1].fl);
    ui->lblWindFx->setText( mWeekWeather[1].fx);
    ui->lblPM25->setText(QString::number(mTodayWeather.pm25));
    ui->lblShiDu->setText(mTodayWeather.shidu);
    ui->lblQuality->setText(mTodayWeather.quality);
     //天气Icon
    ui->lblTypeIcon->setPixmap(mTypeMap[mWeekWeather[1].type]);

    qDebug()<<"Type:"<<mTodayWeather.type;


    for(int i=0;i<6;i++)
    {
        mWeekList[i]->setText("周"+mWeekWeather[i].week.right(1));
        ui->lblWeek0->setText("昨天");
        ui->lblWeek1->setText("今天");
        ui->lblWeek2->setText("明天");

        mDateList[i]->setText(QDateTime::fromString(mWeekWeather[i].date,"yyyy-MM-dd").toString("MM/dd"));
        mTypeList[i]->setText(mWeekWeather[i].type);
        mFlList[i]->setText(mWeekWeather[i].fl);
        mFxList[i]->setText(mWeekWeather[i].fx);
        mIconList[i]->setPixmap(mTypeMap[mWeekWeather[i].type]);

        if(mWeekWeather[i].aqi>0&&mWeekWeather[i].aqi<50)
        {
            mAqiList[i]->setText("优");
            mAqiList[i]->setStyleSheet("background-color:rgb(121,184,0);");
        }
        else if(mWeekWeather[i].aqi>50&&mWeekWeather[i].aqi<100)
        {
            mAqiList[i]->setText("良");
            mAqiList[i]->setStyleSheet("background-color:rgb(255,187,23);");
        }
        else if(mWeekWeather[i].aqi>100&&mWeekWeather[i].aqi<150)
        {
            mAqiList[i]->setText("轻度");
            mAqiList[i]->setStyleSheet("background-color:rgb(255,87,97);");
        }
        else if(mWeekWeather[i].aqi>150&&mWeekWeather[i].aqi<200)
        {
            mAqiList[i]->setText("重度");
            mAqiList[i]->setStyleSheet("background-color:rgb(235,17,27);");
        }
        else
        {
            mAqiList[i]->setText("严重");
            mAqiList[i]->setStyleSheet("background-color:rgb(110,0,0);");
        }
    }


}


bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if(watched==ui->lblHighCurve&&event->type()==QEvent::Paint)
    {
        pointHighCurve();
    }
    if(watched==ui->lblLowCurve&&event->type()==QEvent::Paint)
    {
        pointLowCurve();
    }

    return QWidget::eventFilter(watched,event);
}



void MainWindow::pointHighCurve()
{
    QPainter painter(ui->lblHighCurve);
    painter.setRenderHint(QPainter::Antialiasing,true); //抗锯齿
    int pointX[6]={0};
    for(int i=0;i<6;i++)
    {
        pointX[i]=mWeekList[i]->pos().x()+mWeekList[i]->width()/2;
    }
    int tempSum=0;
    int tempAverage=0;
    for(int i=0;i<6;i++)
    {
        tempSum+= mWeekWeather[i].high;

    }
    tempAverage=tempSum /6;


    int pointY[6]={0};
    int yCenter=ui->lblHighCurve->height()/2;
    for(int i=0;i<6;i++)
    {
        pointY[i] = yCenter-((mWeekWeather[i].high-tempAverage)*INCREEMENT);

        qDebug()<<mWeekWeather[i].high;
    }

    QPen pen=painter.pen();
    pen.setWidth(1);
    pen.setColor(QColor(255,170,0));
    painter.setPen(pen);
    painter.setBrush(QColor(255,170,0));

    for(int i=0;i<6;i++)
    {
        painter.drawEllipse(QPoint(pointX[i],pointY[i]),POINT_RADIUS,POINT_RADIUS);
        painter.drawText(pointX[i]-TEXT_OFFSET_X,pointY[i]-TEXT_OFFSET_Y,QString::number(mWeekWeather[i].high)+"°");
    }

    for(int i=0;i<5;i++)
    {
        if(i==0)
        {
            pen.setStyle(Qt::DotLine);
            painter.setPen(pen);
        }
        else
        {
            pen.setStyle(Qt::SolidLine);
            painter.setPen(pen);
        }
        painter.drawLine(pointX[i],pointY[i],pointX[i+1],pointY[i+1]);
    }
}

void MainWindow::pointLowCurve()
{
    QPainter painter(ui->lblLowCurve);
    painter.setRenderHint(QPainter::Antialiasing,true); //抗锯齿
    int pointX[6]={0};
    for(int i=0;i<6;i++)
    {
        pointX[i]=mWeekList[i]->pos().x()+mWeekList[i]->width()/2;
    }
    int tempSum=0;
    int tempAverage=0;
    for(int i=0;i<6;i++)
    {
        tempSum+= mWeekWeather[i].low;

    }
    tempAverage=tempSum /6;


    int pointY[6]={0};
    int yCenter=ui->lblLowCurve->height()/2;
    for(int i=0;i<6;i++)
    {
        pointY[i] = yCenter-((mWeekWeather[i].low-tempAverage)*INCREEMENT);

        qDebug()<<mWeekWeather[i].low;
    }

    QPen pen=painter.pen();
    pen.setWidth(1);
    pen.setColor(QColor(0,255,255));
    painter.setPen(pen);
    painter.setBrush(QColor(0,255,255));

    for(int i=0;i<6;i++)
    {
        painter.drawEllipse(QPoint(pointX[i],pointY[i]),POINT_RADIUS,POINT_RADIUS);
        painter.drawText(pointX[i]-TEXT_OFFSET_X,pointY[i]-TEXT_OFFSET_Y,QString::number(mWeekWeather[i].low)+"°");
    }

    for(int i=0;i<5;i++)
    {
        if(i==0)
        {
            pen.setStyle(Qt::DotLine);
            painter.setPen(pen);
        }
        else
        {
            pen.setStyle(Qt::SolidLine);
            painter.setPen(pen);
        }
        painter.drawLine(pointX[i],pointY[i],pointX[i+1],pointY[i+1]);
    }
}





void MainWindow::onReplied(QNetworkReply *mReply)
{
    qDebug()<<"OnReplied success";
    int statusCode=mReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if(statusCode!=200)
    {
        QMessageBox::warning(this,"天气请求","请求数据失败",QMessageBox::Ok);

    }
    else
    {
        QByteArray mByteArray= mReply->readAll();
        qDebug()<<"statusCode:"<<statusCode;
        qDebug()<<"rawHeaderList:"<<mReply->rawHeaderList();
        qDebug()<<"mByteArray:"<<mByteArray.data();
        parseJson(mByteArray);

    }
    mReply->deleteLater();

}




void MainWindow::on_btnSearch_clicked()
{
    QString cityName=ui->leCity->text();
    getWeatherInfo(cityName);
}

